<?php

namespace app\admin\controller\yuncunchu;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 文件管理
 *
 * @icon fa fa-file
 * @remark 管理云存储中的文件
 */
class File extends Backend
{
    /**
     * File模型对象
     * @var \app\admin\model\yuncunchu\File
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\yuncunchu\File;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        // 检查权限
        if (!$this->auth->check('yuncunchu/file/index')) {
            $this->error(__('No permission'));
        }
        
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['config'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        // 检查权限
        if (!$this->auth->check('yuncunchu/file/del')) {
            $this->error(__('No permission'));
        }
        
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 使用云存储服务删除文件
                    $service = new \app\common\service\YuncunchuService($item->config_id);
                    $service->delete($item->id);
                    $count++;
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 批量操作
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values) {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds)) {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
                    $count = 0;
                    Db::startTrans();
                    try {
                        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                        foreach ($list as $item) {
                            $count += $item->allowField(true)->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 查看文件详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->with(['config'])->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 下载文件
     */
    public function download($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        try {
            $service = new \app\common\service\YuncunchuService($row->config_id);
            $url = $service->getUrl($row->id);
            
            if ($url) {
                // 重定向到文件URL
                header('Location: ' . $url);
                exit;
            } else {
                $this->error('文件不存在或无法访问');
            }
        } catch (Exception $e) {
            $this->error('下载失败：' . $e->getMessage());
        }
    }

    /**
     * 获取文件统计信息
     */
    public function statistics()
    {
        try {
            $configId = $this->request->get('config_id');
            $service = new \app\common\service\YuncunchuService($configId);
            $stats = $service->getStatistics();
            
            $this->success('获取成功', null, $stats);
        } catch (Exception $e) {
            $this->error('获取统计信息失败：' . $e->getMessage());
        }
    }
}

